from django_redis import get_redis_connection
from rest_framework import serializers

import logging
#日志
logger = logging.getLogger('django')


class ImageCodeCheckSerializer(serializers.Serializer):
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4,min_length=4)

    def validate(self, attrs):
        image_code_id = attrs['image_code_id']
        text = attrs['text']
        #获取链接到redis对象
        redis_conn = get_redis_connection('verify_codes')
        #获取redis中存储的图片验证码
        real_image_code_text = redis_conn.get('img_%s' % image_code_id)
        if not real_image_code_text:
            raise serializers.ValidationError('图片验证码无效')

        #删除图片验证码
        try:
            redis_conn.delete('img_%s' % image_code_id)
        except Exception as e:
            logging.error(e)

        #比较图片验证码,需要先将bytes二进制类型的数据转成字符串
        #py3存储到redis数据库中的数据都是bytes类型的
        real_image_code_text = real_image_code_text.decode()
        if real_image_code_text.lower() != text.lower():
            raise serializers.ValidationError('图片验证码错误')

        #判断是否在60秒内
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            raise serializers.ValidationError('请求次数过于频繁')

        return attrs